package com.xingchen.loveparttimejob.uitls;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.BasicCredentials;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.InputStream;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 小志
 * @date 2024/11/27 - 10:47
 */
public class OssPutUtils {
    //需要访问的地址
    private static final String endpoint   = "https://oss-cn-guangzhou.aliyuncs.com";
    //自己创建的bucket对象
    private static final String bucketName   = "parttimesys";
    //附带密钥的DefaultCredentialProvider
    private static final DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(new BasicCredentials("LTAI5t6bLWVMBYKm7Z7Tn12L", "bVMwdQCGeoejG5QZ59a9l6uveWmak4",null));
    // 创建OSSClient实例。
    private static final OSS ossClient = new OSSClientBuilder().build(endpoint,credentialProvider);

    /**
     * 使用File对象提交
     * @param suffixName 文件名称后缀
     * @param filePath 要传输的file文件
     * @return 文件的url地址路径
     */
    public static String ossPutFiles(String suffixName,File filePath){
        String fileName = generateRandomFileName(suffixName);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,filePath);
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            if(result.getETag() != null){
                return  "https://parttimesys.oss-cn-guangzhou.aliyuncs.com/"+fileName;
            }else{
                return null;
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 使用inputStream提交
     * @param suffixName  文件名称后缀
     * @param inputStream 要传输的inputStream文件
     * @return 文件的url地址路径
     */
    public static String ossPutInputStream(String suffixName, InputStream inputStream){
        String fileName = generateRandomFileName(suffixName);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,inputStream);
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            if(result.getETag() != null){
                return  "https://parttimesys.oss-cn-guangzhou.aliyuncs.com/"+fileName;
            }else{
                return null;
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 生成不重复的文件名
     * @param suffixName 文件名称后缀
     * @return 不重复字符串
     */
    private static String generateRandomFileName(String suffixName) {
        // 获取当前时间戳（以毫秒为单位）
        long timestamp = System.currentTimeMillis();
        // 生成一个随机数
        int randomNum = ThreadLocalRandom.current().nextInt(1000, 9999);
        // 组合时间戳和随机数，并加上图片的扩展名
        return timestamp + "_" + randomNum + suffixName;
    }
}
